//
//  MuyuViewController.m
//  CangLongWnnianli
//
//  Created by 暗流澎涌 on 2025/7/9.
//

#import "MuyuViewController.h"

@interface MuyuViewController ()

@end

@implementation MuyuViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.autoKnockInterval = 1.0; // 默认间隔1秒
    [self setupUI];
    [self setupConstraints];
    [self generateMuyuAudioFile];
}

- (void)setupUI {
    self.view.backgroundColor = [UIColor blackColor];
    
    // 背景图片
    self.backgroundImageView = [[UIImageView alloc] init];
    self.backgroundImageView.image = [UIImage imageNamed:@"beijing"];
    self.backgroundImageView.contentMode = UIViewContentModeScaleAspectFill;
    [self.view addSubview:self.backgroundImageView];
    
    // 返回按钮
    self.backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.backButton setImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    [self.backButton addTarget:self action:@selector(backButtonTapped) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.backButton];
    
    // 标题
    self.titleLabel = [[UILabel alloc] init];
    self.titleLabel.text = @"木鱼";
    self.titleLabel.textColor = [UIColor colorWithRed:0.9 green:0.8 blue:0.6 alpha:1.0];
    self.titleLabel.font = [UIFont systemFontOfSize:24 weight:UIFontWeightMedium];
    self.titleLabel.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:self.titleLabel];
    
    // 木鱼图片
    self.muyuImageView = [[UIImageView alloc] init];
    self.muyuImageView.image = [UIImage imageNamed:@"muyu"];
    self.muyuImageView.contentMode = UIViewContentModeScaleAspectFit;
    self.muyuImageView.userInteractionEnabled = YES;
    
    // 木槌图片 - 添加在木鱼图片之后
    self.hammerImageView = [[UIImageView alloc] init];
    self.hammerImageView.image = [UIImage imageNamed:@"chuizi"];
    self.hammerImageView.contentMode = UIViewContentModeScaleAspectFit;
    self.hammerImageView.alpha = 0.0; // 初始隐藏
    [self.view addSubview:self.hammerImageView];
    
    // 添加点击手势
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(muyuTapped)];
    [self.muyuImageView addGestureRecognizer:tapGesture];
    [self.view addSubview:self.muyuImageView];
    
    // 自动敲击标签
    self.autoKnockLabel = [[UILabel alloc] init];
    self.autoKnockLabel.text = @"自动敲击";
    self.autoKnockLabel.textColor = [UIColor whiteColor];
    self.autoKnockLabel.font = [UIFont systemFontOfSize:16];
    [self.view addSubview:self.autoKnockLabel];
    
    // 自动敲击开关
    self.autoKnockSwitch = [[UISwitch alloc] init];
    self.autoKnockSwitch.onTintColor = [UIColor redColor];
    [self.autoKnockSwitch addTarget:self action:@selector(autoKnockSwitchChanged:) forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:self.autoKnockSwitch];
    
    // 更多木鱼样式按钮
    self.moreStyleButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.moreStyleButton setTitle:@"更多木鱼样式" forState:UIControlStateNormal];
    [self.moreStyleButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    self.moreStyleButton.backgroundColor = [UIColor redColor];
    self.moreStyleButton.layer.cornerRadius = 25;
    self.moreStyleButton.titleLabel.font = [UIFont systemFontOfSize:16];
    [self.moreStyleButton addTarget:self action:@selector(moreStyleButtonTapped) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.moreStyleButton];
    
    // 自动敲击间隔按钮
    self.autoIntervalButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.autoIntervalButton setTitle:@"自动敲击间隔" forState:UIControlStateNormal];
    [self.autoIntervalButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    self.autoIntervalButton.backgroundColor = [UIColor colorWithRed:0.4 green:0.2 blue:0.1 alpha:1.0];
    self.autoIntervalButton.layer.cornerRadius = 25;
    self.autoIntervalButton.titleLabel.font = [UIFont systemFontOfSize:16];
    [self.autoIntervalButton addTarget:self action:@selector(autoIntervalButtonTapped) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.autoIntervalButton];
    
    // 隐藏导航栏
    self.navigationController.navigationBarHidden = YES;
}

- (void)setupConstraints {
    // 背景图片 - 填满整个视图
    [self.backgroundImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
    // 返回按钮 - 左上角
//    [self.backButton mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.equalTo(self.view.mas_safeAreaLayoutGuideTop).offset(10);
//        make.left.equalTo(self.view).offset(20);
//        make.size.mas_equalTo(CGSizeMake(40, 40));
//    }];
    
    // 标题 - 顶部居中
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_safeAreaLayoutGuideTop).offset(20);
        make.centerX.equalTo(self.view);
    }];
    
    // 木鱼图片 - 屏幕中央偏上
    [self.muyuImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.centerY.equalTo(self.view).offset(-50);
        make.size.mas_equalTo(CGSizeMake(200, 120));
    }];
    
    // 木槌约束 - 位于木鱼上方偏右位置
    [self.hammerImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.muyuImageView).offset(30);
        make.bottom.equalTo(self.muyuImageView.mas_top).offset(20);
        make.size.mas_equalTo(CGSizeMake(120, 120)); // 从80x80调整为120x120
    }];
    
    // 自动敲击标签 - 木鱼下方
    [self.autoKnockLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.muyuImageView.mas_bottom).offset(80);
        make.centerX.equalTo(self.view).offset(-30);
    }];
    
    // 自动敲击开关 - 标签右侧
    [self.autoKnockSwitch mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.autoKnockLabel);
        make.left.equalTo(self.autoKnockLabel.mas_right).offset(20);
    }];
    
    // 更多样式按钮 - 左下角
    [self.moreStyleButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(40);
        make.top.equalTo(self.autoKnockLabel.mas_bottom).offset(60);
        make.size.mas_equalTo(CGSizeMake(140, 50));
    }];
    
    // 自动间隔按钮 - 右下角
    [self.autoIntervalButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.view).offset(-40);
        make.centerY.equalTo(self.moreStyleButton);
        make.size.mas_equalTo(CGSizeMake(140, 50));
    }];
}

#pragma mark - 音频生成和播放

- (void)generateMuyuAudioFile {
    // 生成木鱼敲击音效
    NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    NSString *audioPath = [documentsPath stringByAppendingPathComponent:@"muyu_sound.wav"];
    
    // 检查文件是否已存在
    if ([[NSFileManager defaultManager] fileExistsAtPath:audioPath]) {
        [self setupAudioPlayer:audioPath];
        return;
    }
    
    // 音频参数
    Float64 sampleRate = 44100.0;
    Float32 duration = 0.4; // 0.4秒
    UInt32 numSamples = (UInt32)(sampleRate * duration);
    
    // 创建音频数据
    Float32 *audioData = malloc(numSamples * sizeof(Float32));
    
    for (UInt32 i = 0; i < numSamples; i++) {
        Float32 t = (Float32)i / sampleRate;
        
        // 生成木鱼音效：低频基音 + 高频泛音 + 衰减包络
        Float32 fundamental = sin(2.0 * M_PI * 180.0 * t); // 180Hz基音
        Float32 harmonic1 = 0.6 * sin(2.0 * M_PI * 360.0 * t); // 360Hz泛音
        Float32 harmonic2 = 0.4 * sin(2.0 * M_PI * 720.0 * t); // 720Hz泛音
        Float32 harmonic3 = 0.3 * sin(2.0 * M_PI * 1440.0 * t); // 1440Hz泛音
        Float32 click = 0.2 * sin(2.0 * M_PI * 3000.0 * t) * exp(-t * 15.0); // 高频点击音
        
        // 指数衰减包络
        Float32 envelope = exp(-t * 6.0);
        
        // 添加一些噪声模拟木质感
        Float32 noise = ((Float32)arc4random() / UINT32_MAX - 0.5) * 0.05 * envelope;
        
        // 合成最终音效
        audioData[i] = (fundamental + harmonic1 + harmonic2 + harmonic3 + click + noise) * envelope * 0.25;
    }
    
    // 写入WAV文件
    [self writeWAVFile:audioPath withData:audioData numSamples:numSamples sampleRate:sampleRate];
    
    free(audioData);
    [self setupAudioPlayer:audioPath];
}

- (void)writeWAVFile:(NSString *)filePath withData:(Float32 *)data numSamples:(UInt32)numSamples sampleRate:(Float64)sampleRate {
    NSMutableData *wavData = [NSMutableData data];
    
    // WAV文件头
    UInt32 dataSize = numSamples * 2; // 16位音频
    UInt32 fileSize = dataSize + 36;
    
    // RIFF头
    [wavData appendBytes:"RIFF" length:4];
    [wavData appendBytes:&fileSize length:4];
    [wavData appendBytes:"WAVE" length:4];
    
    // fmt块
    [wavData appendBytes:"fmt " length:4];
    UInt32 fmtSize = 16;
    [wavData appendBytes:&fmtSize length:4];
    UInt16 audioFormat = 1; // PCM
    [wavData appendBytes:&audioFormat length:2];
    UInt16 numChannels = 1; // 单声道
    [wavData appendBytes:&numChannels length:2];
    UInt32 sampleRateInt = (UInt32)sampleRate;
    [wavData appendBytes:&sampleRateInt length:4];
    UInt32 byteRate = sampleRateInt * numChannels * 2;
    [wavData appendBytes:&byteRate length:4];
    UInt16 blockAlign = numChannels * 2;
    [wavData appendBytes:&blockAlign length:2];
    UInt16 bitsPerSample = 16;
    [wavData appendBytes:&bitsPerSample length:2];
    
    // data块
    [wavData appendBytes:"data" length:4];
    [wavData appendBytes:&dataSize length:4];
    
    // 音频数据（转换为16位整数）
    for (UInt32 i = 0; i < numSamples; i++) {
        SInt16 sample = (SInt16)(data[i] * 32767.0);
        [wavData appendBytes:&sample length:2];
    }
    
    [wavData writeToFile:filePath atomically:YES];
}

- (void)setupAudioPlayer:(NSString *)audioPath {
    NSError *error;
    NSURL *audioURL = [NSURL fileURLWithPath:audioPath];
    self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:audioURL error:&error];
    
    if (error) {
        NSLog(@"音频播放器初始化失败: %@", error.localizedDescription);
    } else {
        [self.audioPlayer prepareToPlay];
        // 设置音频会话
        [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
        [[AVAudioSession sharedInstance] setActive:YES error:nil];
    }
}

- (void)playKnockSound {
    if (self.audioPlayer) {
        [self.audioPlayer stop];
        self.audioPlayer.currentTime = 0;
        [self.audioPlayer play];
    }
}

#pragma mark - Actions

- (void)muyuTapped {
    self.knockCount++;
    
    // 播放音效
    [self playKnockSound];
    
    // 木槌敲击动画
    [self performHammerKnockAnimation];
    
    // 木鱼被敲击动画
    [UIView animateWithDuration:0.1 animations:^{
        self.muyuImageView.transform = CGAffineTransformMakeScale(0.95, 0.95);
    } completion:^(BOOL finished) {
        [UIView animateWithDuration:0.1 animations:^{
            self.muyuImageView.transform = CGAffineTransformIdentity;
        }];
    }];
    
    // 添加粒子效果
    [self addKnockParticleEffect];
    
    // 添加震动反馈
    if (@available(iOS 10.0, *)) {
        UIImpactFeedbackGenerator *feedbackGenerator = [[UIImpactFeedbackGenerator alloc] initWithStyle:UIImpactFeedbackStyleMedium];
        [feedbackGenerator impactOccurred];
    }
    
    NSLog(@"木鱼被敲击了 %ld 次", (long)self.knockCount);
}

// 新增木槌敲击动画方法
- (void)performHammerKnockAnimation {
    // 重置木槌位置和透明度
    self.hammerImageView.alpha = 1.0;
    self.hammerImageView.transform = CGAffineTransformMakeRotation(-M_PI_4); // 初始倾斜45度
    
    // 第一阶段：木槌向下敲击
    [UIView animateWithDuration:0.15 delay:0 options:UIViewAnimationOptionCurveEaseIn animations:^{
        // 旋转到垂直位置并稍微向下移动
        self.hammerImageView.transform = CGAffineTransformMakeRotation(0);
        CGAffineTransform moveDown = CGAffineTransformMakeTranslation(0, 15);
        self.hammerImageView.transform = CGAffineTransformConcat(self.hammerImageView.transform, moveDown);
    } completion:^(BOOL finished) {
        // 第二阶段：木槌反弹回原位
        [UIView animateWithDuration:0.2 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
            // 回到初始倾斜位置
            self.hammerImageView.transform = CGAffineTransformMakeRotation(-M_PI_4);
        } completion:^(BOOL finished) {
            // 第三阶段：淡出木槌
            [UIView animateWithDuration:0.3 delay:0.1 options:UIViewAnimationOptionCurveEaseOut animations:^{
                self.hammerImageView.alpha = 0.0;
            } completion:nil];
        }];
    }];
}

- (void)addKnockParticleEffect {
    // 创建粒子效果
    for (int i = 0; i < 8; i++) {
        UIView *particle = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 6, 6)];
        particle.backgroundColor = [UIColor colorWithRed:1.0 green:0.8 blue:0.4 alpha:0.9];
        particle.layer.cornerRadius = 3;
        particle.center = self.muyuImageView.center;
        [self.view addSubview:particle];
        
        // 随机方向和距离
        CGFloat angle = (CGFloat)i * M_PI * 2 / 8;
        CGFloat distance = 40 + arc4random_uniform(30);
        CGFloat endX = particle.center.x + cos(angle) * distance;
        CGFloat endY = particle.center.y + sin(angle) * distance;
        
        [UIView animateWithDuration:0.6 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
            particle.center = CGPointMake(endX, endY);
            particle.alpha = 0;
            particle.transform = CGAffineTransformMakeScale(0.1, 0.1);
        } completion:^(BOOL finished) {
            [particle removeFromSuperview];
        }];
    }
}

- (void)autoKnockSwitchChanged:(UISwitch *)sender {
    if (sender.isOn) {
        // 开启自动敲击
        self.autoKnockTimer = [NSTimer scheduledTimerWithTimeInterval:self.autoKnockInterval
                                                               target:self
                                                             selector:@selector(autoKnock)
                                                             userInfo:nil
                                                              repeats:YES];
    } else {
        // 关闭自动敲击
        [self.autoKnockTimer invalidate];
        self.autoKnockTimer = nil;
    }
}

- (void)autoKnock {
    [self muyuTapped];
}

- (void)moreStyleButtonTapped {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"选择木鱼样式"
                                                                   message:@"请选择您喜欢的木鱼样式"
                                                            preferredStyle:UIAlertControllerStyleActionSheet];
    
    [alert addAction:[UIAlertAction actionWithTitle:@"经典木鱼" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        self.muyuImageView.image = [UIImage imageNamed:@"muyu"];
    }]];
    
    [alert addAction:[UIAlertAction actionWithTitle:@"金色木鱼" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        // 可以添加其他样式的木鱼图片
        self.muyuImageView.image = [UIImage imageNamed:@"muyu"];
    }]];
    
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    
    // iPad适配
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
        alert.popoverPresentationController.sourceView = self.moreStyleButton;
        alert.popoverPresentationController.sourceRect = self.moreStyleButton.bounds;
    }
    
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)autoIntervalButtonTapped {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"设置敲击间隔"
                                                                   message:@"请选择自动敲击的时间间隔"
                                                            preferredStyle:UIAlertControllerStyleActionSheet];
    
    NSArray *intervals = @[@"0.5秒", @"1秒", @"2秒", @"3秒"];
    NSArray *values = @[@0.5, @1.0, @2.0, @3.0];
    
    for (int i = 0; i < intervals.count; i++) {
        [alert addAction:[UIAlertAction actionWithTitle:intervals[i] style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            self.autoKnockInterval = [values[i] doubleValue];
            if (self.autoKnockTimer) {
                [self.autoKnockTimer invalidate];
                self.autoKnockTimer = [NSTimer scheduledTimerWithTimeInterval:self.autoKnockInterval
                                                                       target:self
                                                                     selector:@selector(autoKnock)
                                                                     userInfo:nil
                                                                      repeats:YES];
            }
        }]];
    }
    
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    
    // iPad适配
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
        alert.popoverPresentationController.sourceView = self.autoIntervalButton;
        alert.popoverPresentationController.sourceRect = self.autoIntervalButton.bounds;
    }
    
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)backButtonTapped {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)dealloc {
    [self.autoKnockTimer invalidate];
}

@end
